package com.craiglarman.monopoly.domain;

import java.util.ArrayList;
import java.util.List;

public class MGame {
	
	static final String OUT_DICE_SEP = ",";
	public  static final String MSG_UNSUPPORTED_ROUND_NUM = "Unsupported Round Number";
	
	public static final int MIN_ROUND = 0;	
	public static final int MAX_ROUND = 5;
	public static final int DICE_COUNT = 2;
	
	 int currentRound= MIN_ROUND;
	 Board board = new Board();
	 List<Player> players ;
	 List<String> outputResult = new ArrayList<String>();
	 List<Die> dice = new ArrayList<Die>(DICE_COUNT);
	
	public MGame() {
		for(int i=0;i<DICE_COUNT;i++){
			Die die = new Die();
			dice.add(die);
		}
	}

	private void initPlayers(int numberOfPlayers) {
		players = new ArrayList<Player>(numberOfPlayers);
		for(int i=0;i<numberOfPlayers;i++){
			Player p = new Player(board, dice);
			players.add(p);
		}
	}

	public Board getBoard() {
		return this.board;
	}

	public int getPlayersCount() {
		return players.size();
	}

	public int getCurrentRound() {
		return currentRound;
	}

	private void playRound() {
		
		StringBuilder roundResult = new StringBuilder();
		
		int countPlayer = 0;
		
		for (Player player : players) {
			
			player.takeTurn();
			
			int diceTotal = player.getDiceTotal();
			
			countPlayer++;
			
			roundResult.append(diceTotal);
			
			boolean notlastPlayer = (countPlayer!=this.players.size());
			
			if (notlastPlayer) roundResult.append(OUT_DICE_SEP);
		}
		
		outputResult.add(roundResult.toString());
		
	}
	
	public Player getPlayer(int i) {
		return players.get(i);
	}

	public List<Player> getAllPlayers() {
		return players;
	}
	
	public void play(int rounds,int numberOfPlayers) {
		initPlayers(numberOfPlayers);
		
		if (rounds<=MAX_ROUND) {
			while(currentRound<rounds) {
				playRound();
				currentRound++;
			}
		}
	}
	
	public List<String> getOutputResult() {
		return outputResult;
	}
	

}
